package com.spm.librarianmanagersystem.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.spm.librarianmanagersystem.config.aop.WebLog;
import com.spm.librarianmanagersystem.mapper.MemberMapper;
import com.spm.librarianmanagersystem.pojo.Book;
import com.spm.librarianmanagersystem.service.BookService;
import com.spm.librarianmanagersystem.service.BorrowService;
import com.spm.librarianmanagersystem.service.impl.BookServiceImpl;
import com.spm.librarianmanagersystem.utils.JsonResult;
import com.spm.librarianmanagersystem.utils.UserContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
public class BorrowController {
    @Autowired
    private BorrowService borrowService;
    @Autowired
    MemberMapper memberMapper;
    @Autowired
    BookService bookService;

    @WebLog(description = "borrow")
    @PostMapping("/api/user/borrow")
    public JsonResult<Integer> borrrow(@RequestBody JSONObject borrowMap) {
        String currentUserId = UserContextHolder.getCurrentUserId();
        Integer borrowId = 0;
        try {
            borrowId = borrowService.borrowBook(currentUserId, borrowMap);
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult<>(0, -1, e.getMessage());
        }
        return new JsonResult<>(borrowId);
    }

    @GetMapping("/api/user/borrowing")
    public JsonResult<JSONArray> getBorrowingList(){
        String currentUserId = UserContextHolder.getCurrentUserId();
        return new JsonResult<>(borrowService.getBorrowingList(currentUserId));
    }

    @GetMapping("/api/user/borrowing/history")
    public JsonResult<JSONArray> getBorrowHistory(){
        String currentUserId = UserContextHolder.getCurrentUserId();
        return new JsonResult<>(borrowService.getBorrowHistory(currentUserId));
    }

    @GetMapping("/api/user/borrowing/detail")
    public JsonResult<JSONObject> getBorrowRecordDetail(@RequestParam("borrowing_id")Integer borrowingId){
        return new JsonResult<>(borrowService.getBorrowRecordDetail(borrowingId));
    }


    @GetMapping(value = "/api/user/borrowing/score")
    public JsonResult updateBook(@RequestParam("borrowing_id")Integer borrowingId, @RequestParam("ISBN")String ISBN, @RequestParam("score")Double score){
        borrowService.updateScore(borrowingId, score);
        bookService.updateScore(ISBN);
        return new JsonResult();
    }

}
